<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'

// 定义待办项类型
interface Todo {
  id: number
  title: string
  completed: boolean
}

// 创建响应式待办列表
const todos = reactive<Todo[]>([
  { id: 1, title: '学习 Vue3 ref', completed: true },
  { id: 2, title: '掌握 reactive', completed: true },
  { id: 3, title: '理解 computed', completed: false },
  { id: 4, title: '学会 watch', completed: false }
])

// 新待办项标题
const newTodoTitle = ref('')

// 计算未完成的待办项数量
const remainingCount = computed(() => {
  return todos.filter(todo => !todo.completed).length
})

// 计算完成百分比
const completionPercentage = computed(() => {
  if (todos.length === 0) return 0
  return Math.round((todos.filter(todo => todo.completed).length / todos.length) * 100)
})

// 添加新待办项
const addTodo = () => {
  if (newTodoTitle.value.trim()) {
    todos.push({
      id: Date.now(), // 使用时间戳作为唯一ID
      title: newTodoTitle.value.trim(),
      completed: false
    })
    newTodoTitle.value = '' // 清空输入框
  }
}

// 切换待办项状态
const toggleTodo = (id: number) => {
  const todo = todos.find(t => t.id === id)
  if (todo) {
    todo.completed = !todo.completed
  }
}

// 删除待办项
const deleteTodo = (id: number) => {
  const index = todos.findIndex(t => t.id === id)
  if (index !== -1) {
    todos.splice(index, 1)
  }
}

// 清空已完成的待办项
const clearCompleted = () => {
  const completedIndices = todos
    .map((todo, index) => todo.completed ? index : -1)
    .filter(index => index !== -1)
    .reverse() // 从后往前删除，避免索引变化问题
  
  completedIndices.forEach(index => {
    todos.splice(index, 1)
  })
}

// 监听待办列表变化，在控制台输出统计信息
watch(() => todos.length, (newLength, oldLength) => {
  console.log(`待办列表发生变化：从 ${oldLength} 项变为 ${newLength} 项`)
})

watch(() => remainingCount.value, (newCount) => {
  console.log(`剩余未完成待办：${newCount} 项`)
})
</script>

<template>
  <div class="card">
    <h2>🏆 作业2｜待办列表 - 剩余未完成数自动统计</h2>
    
    <div class="todo-app">
      <!-- 添加新待办项 -->
      <div class="add-todo">
        <input 
          v-model="newTodoTitle"
          @keyup.enter="addTodo"
          placeholder="添加新的待办事项..."
          type="text"
        />
        <button @click="addTodo" :disabled="!newTodoTitle.trim()">添加</button>
      </div>
      
      <!-- 进度统计 -->
      <div class="todo-stats">
        <p>剩余未完成: {{ remainingCount }} / {{ todos.length }}</p>
        <div class="progress-bar">
          <div 
            class="progress-fill" 
            :style="{ width: completionPercentage + '%' }"
          ></div>
        </div>
        <p>完成度: {{ completionPercentage }}%</p>
      </div>
      
      <!-- 待办列表 -->
      <div class="todo-list" v-if="todos.length > 0">
        <div 
          v-for="todo in todos" 
          :key="todo.id" 
          class="todo-item"
          :class="{ 'completed': todo.completed }"
        >
          <label class="todo-checkbox">
            <input 
              type="checkbox" 
              :checked="todo.completed" 
              @change="toggleTodo(todo.id)"
            />
            <span class="todo-title">{{ todo.title }}</span>
          </label>
          <button @click="deleteTodo(todo.id)" class="delete-btn">删除</button>
        </div>
      </div>
      
      <!-- 空状态提示 -->
      <div v-else class="empty-state">
        <p>🎉 没有待办事项了！添加一些新的任务吧！</p>
      </div>
      
      <!-- 操作按钮 -->
      <div class="todo-actions" v-if="todos.length > 0">
        <button @click="clearCompleted" class="clear-btn">
          清空已完成
        </button>
      </div>
    </div>
    
    <div class="explanation">
      <h4>📝 实现要点</h4>
      <ul>
        <li>使用 reactive 创建待办项数组</li>
        <li>使用 computed 计算未完成数量和完成百分比</li>
        <li>使用 watch 监听待办列表变化</li>
        <li>实现添加、删除、切换状态等功能</li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
.todo-app {
  margin: 2em 0;
}

.add-todo {
  display: flex;
  gap: 10px;
  margin-bottom: 1em;
}

.add-todo input {
  flex: 1;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #ccc;
  font-size: 1em;
}

.todo-stats {
  margin: 1em 0;
  padding: 1em;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #444;
  border-radius: 10px;
  overflow: hidden;
  margin: 10px 0;
}

.progress-fill {
  height: 100%;
  background-color: #4caf50;
  transition: width 0.3s ease;
}

.todo-list {
  max-height: 300px;
  overflow-y: auto;
  margin: 1em 0;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin: 5px 0;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  transition: background-color 0.3s;
}

.todo-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.todo-item.completed .todo-title {
  text-decoration: line-through;
  color: #888;
}

.todo-checkbox {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  cursor: pointer;
}

.delete-btn {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.clear-btn {
  background-color: #ff9800;
  color: white;
}

.empty-state {
  padding: 2em;
  color: #888;
}

.explanation {
  text-align: left;
  margin-top: 2em;
}
</style>